// logs.js
const util = require('../../utils/util.js')
const client=require('../../utils/client.js')
const server=require('../../utils/server.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
let App = getApp();
Page({
  data: {
    server:'',
    login:false,
    userInfo:{},
    ld:'',
    wgStatus:'3',
    erweima:false,
    img:'',
    xz:'',
    cj:'',
    type:1,
    isClose:2,
    isRent:2,
    kd:'',
    havaInfo:true,
    xzList:[],
    xq:'',
    danyuan:'',
    shi:'',
    lat:'',
    long:'',
    typeText:'',
    replaceName:'',
    needLogin:false,
    isNeedOpenLocation:false
  },
  onLoad() {
    console.log('login',this.data.login)
    let url=getApp().globalData.server;
    this.setData({server:url})
    let user=server.getUserToken();
    if(user){
        this.checkLogin();
    }
    // this.getLocation();
  },
  // 分享给朋友
  onShareAppMessage: function (res) {
    return {
      title: "苍南基层防疫微网格助手",
      path: 'pages/home/home',
      imageUrl:'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-767674fd-0f0e-4801-90e6-bef27c2e36df/c5fa5671-bc58-4469-b3c4-4e7bd255e547.png',
      success: function (res) {
        console.log("分享成功")
      },
      fail: function (res) {
        console.log("分享失败")
      }
    }
  },
  // 分享到朋友圈 
  onShareTimeline: function() {
    return {
      title: '苍南基层防疫微网格助手',
      path: 'pages/home/home',
      imageUrl:'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-767674fd-0f0e-4801-90e6-bef27c2e36df/c5fa5671-bc58-4469-b3c4-4e7bd255e547.png'
    }
  },
  changeIsClose: function(e) {
    console.log('e',e)
    this.setData({
      isClose: e.detail.value
    })
    console.log(this.data.isClose)
  },
  changeIsRent: function(e) {
    console.log('e',e)
    this.setData({
      isRent: e.detail.value
    })
    console.log(this.data.isRent)
  },
  changeTypeIll:function(e){
    console.log('e',e)
    this.setData({
      type:e.detail.value
    })
    wx.setStorageSync('type', e.detail.value)
    if(e.detail.value==3){
      this.setData({
        isRent:2
      })
    }
  },
  bindCJInput: function(e) {
    if(!this.data.login){
      this.setData({needLogin:true})
      // wx.showModal({
      //   title: '友情提示',
      //   content: '请先点登录',
      //   showCancel:false,
      //   success: function (res) {
      //     console.log('res',res)
      //     if(res.confirm){

      //     }
      //   }
      // });
      return;
    }
    this.setData({
      cj: e.detail.value.replace(/\s*/g,"")
    })
    console.log(this.data.cj)
  },
  bindXZChange: function(e) {
    if(!this.data.login){
      this.setData({needLogin:true})
      return;
    }
    if(!this.data.lat){
      this.getLocation()
      return
    }
    console.log('e.detail.value',e.detail.value)
    this.setData({
      xz: this.data.xzList[e.detail.value]
    })
  },
  checkLogin(){
    // wx.request({url:'http://127.0.0.1:8080/app/wx/checkLogin',method:"get"})
    client.request('/app/wx/checkLogin','get',{},(data)=>{
        if(data.code==0){
          this.setData({login:true,userInfo:data.data,wgStatus:data.data.wgStatus})
          this.setData({
            replaceName:this.repaceStar(data.data.name)
          })
          server.setUserToken(data.data);
        }else{
          server.clearUserToken();
        }
    },(e)=>{
      console.log(e);
    })
  },
  getPhoneLogin(e){
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      return;
    }
    let _that=this;
    let ivObj=e.detail.iv;
    let telObj=e.detail.encryptedData;
    
    wx.login({
      fail(res){
        console.log(res);
      },
      success(res){
        let code=res.code;
        wx.getUserInfo({
          success(res){
            var userInfo = res.userInfo;
            var nickName = userInfo.nickName;
            var avatar=userInfo.avatarUrl;
            let userToken= server.getUserToken();
            let header={};
            if(userToken){
              header.TToken=userToken.token;
            }
            wx.request({
              url: server.baseUrl+'/app/wx/login',
              method:'get',
              header:header,
              data:{
                code: code,
                tel:telObj,
                iv:ivObj,
                name:'',
                avatar:avatar
              },
              success:(res)=>{
                let data=res.data;
                if(data.code==0){
                  let user=data.data;
                  user.avatarUrl=userInfo.avatarUrl;
                  server.setUserToken(user);
                  if(user.name==''){
                    user.name=nickName;
                  }
                  _that.setData({login:true,userInfo:user,wgStatus:user.wgStatus,needLogin:false});
                  _that.setData({replaceName:_that.repaceStar(user.name)})
                }
              }
            })
          }
      })
      }
    })
  },
  goAddress(){
    if(!this.data.login){
      // wx.showModal({
      //   title: '友情提示',
      //   content: '请先点登录',
      //   showCancel:false,
      //   success: function (res) {
      //     console.log('res',res)
      //     if(res.confirm){

      //     }
      //   }
      // });
      this.setData({needLogin:true})
      return;
    }
    wx.navigateTo({
      url: '/pages/addAddress/addAddress',
    });
  },
  onShow(){
    this.checkLogin();

    let _that=this;
    this.setData({typeText:wx.getStorageSync('typeText')})
    let n=[];
    client.request('/app/wx/xz','get',{},(d)=>{
      d.data.forEach((e)=>{
        n.push(e.display);        
      })
      _that.setData({
        xzList:n
      })
    })
   this.initData();
  },
  repaceStar(str) {
    // if(val.substr(1,1)){
    //   return val.substr(0,1)+"*"+val.substr(1,1)
    // }else{
    //   return val.substr(0,1)+"*"
    // }
    if(null != str && str != undefined){
        if(str.length==2){
            return str.substring(0,1)+'*' //截取name 字符串截取第一个字符，
        }else if(str.length==3){
            return str.substring(0,1)+"*"+str.substring(2,3)//截取第一个和第三个字符
        }else if(str.length>3){
            return str.substring(0,1)+"*"+'*'+str.substring(3,str.length)//截取第一个和大于第4个字符
        }
    } else {
        return "";
    }
  },
  goApply(){
    let _that=this;
    // wx.getLocation({
    //   type:'gcj02',
    //   success(res){
    //     //纬度
    //     let lat=res.latitude;
    //     //精度
    //     let long=res.longitude;
    //     _that.setData({ld:long+'-'+lat})
    //   }
    // })
    if(!this.data.login){
      // wx.showModal({
      //   title: '友情提示',
      //   content: '请先点登录',
      //   showCancel:false,
      //   success: function (res) {
      //     console.log('res',res)
      //     if(res.confirm){

      //     }
      //   }
      // });
      this.setData({needLogin:true})
      return;
    }
    wx.navigateTo({
      url: '/pages/apply/apply',
    });
  },
  getLocation(){
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success(res) {//经过测试在PC上定位不准确，在手机上就准确了
        // var location = dingwei.gcj02towgs84(res.longitude, res.latitude);//如果定位不准确的解决方法
        const longitude = res.longitude;
        const latitude = res.latitude;
        that.setData({lat:latitude,long:longitude});
        wx.setStorageSync('lat', latitude);
        wx.setStorageSync('long', longitude);
        
        // that.setData({
        //   longitude: longitude,
        //   latitude: latitude
        // })
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
          //此key需要用户自己申请
          // key: '4AFBZ-OADKJ-SAZFN-KYM6M-F6IV3-7ABJ7'
          key:'6ZUBZ-UABCD-YLF4U-HQ2IM-M3H2V-5DFSD'
        });
        // console.log('qqmapsdk')
        // 调用接口
        that.pointToAddress(longitude, latitude, function (res) {
          console.log('pointToAddress',res)
          // 得到最终地址
          // console.log(res, "得到最终地址");
          that.setData({
            ld: `${res.address}`
            // ld: `${res.address_component.province},${res.address_component.city},${res.address_component.district}`
          })
          wx.setStorageSync('ld', res.address)
          // console.log(that.data.region, "region")
          // wx.setStorageSync('region', that.data.region)
        })
      },
      fail(res){
        console.log('res',res)
        if(res.errCode==2){
          that.setData({isNeedOpenLocation:true})
          if(that.data.isNeedOpenLocation){
            wx.showModal({
              title: '友情提示',
              content: '请先在系统设置中开启手机自带的定位功能',
              showCancel:false,
              success: function (res) {
                console.log('res',res)
                if(res.confirm){
      
                }
              }
            });
            return
          }
        }
      }
    })
  },
  // 定义 pointToAddress 方法
  pointToAddress: function (longitude, latitude, callback) {
    var _this = this;
    // 调用接口
    qqmapsdk.reverseGeocoder({
      location: {
        longitude: longitude,
        latitude: latitude
      },
      success: function (res) {
        // 解析成功返回地址
        callback(res.result);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  luru(){
    if(!this.data.login){
      this.setData({needLogin:true})
      // wx.showModal({
      //   title: '友情提示',
      //   content: '请先点登录',
      //   showCancel:false,
      //   success: function (res) {
      //     console.log('res',res)
      //     if(res.confirm){

      //     }
      //   }
      // });
      return;
    }
    if(!this.data.wzinfo){
      wx.showModal({
        content: '请先添加排查点',showCancel:false
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/checkIn/checkIn?a=2',
    });
  },
  scane(e){
    if(!this.data.login){
      this.setData({needLogin:true})
      // wx.showModal({
      //   title: '友情提示',
      //   content: '请先点登录',
      //   showCancel:false,
      //   success: function (res) {
      //     console.log('res',res)
      //     if(res.confirm){

      //     }
      //   }
      // });
      return;
    }
    if(!this.data.wzinfo){
      wx.showModal({
        content: '请先添加排查点',showCancel:false
      })
      return;
    }
  
    let _that=this;
    try{
      wx.scanCode({
        onlyFromCamera: true,
        success:res=>{
          let content=res.result;
          client.request('/app/wx/scan/v2','post',{'code':content},(data)=>{
            console.log(data);
            if(data.code==0){
              let info=data.data;
              let name=info.name;
              let status=info.status;
              let card=info.card;
              let phone=info.phone;

              // wx.navigateTo({
              //   url: '/pages/checkIn/checkIn?name='+name+"&m="+status+"&card="+card+"&phone="+phone+"&a=1",
              // });
              let zname=info.zname;
              let nidcardNo=info.nidcardNo;
              let nphone=info.nphone;

              console.log(info);
              wx.navigateTo({
                url: '/pages/checkInScane/checkInScane?name='+name+"&m="+status+"&card="+card+"&phone="+phone+"&a=1"+"&zname="+zname+"&nidcardNo="+nidcardNo+"&nphone="+nphone,
              });
            }else{
              wx.showModal({
                content: data.msg,showCancel:false,
              })
            
            }
          }
          )
        }
      });
    }finally{
     
    }
  },
  feedback() {
    if(!this.data.login){
      this.setData({needLogin:true})
      return;
    }
    wx.navigateTo({
      url: '/pages/feedback/feedback',
    });
  },
  ewm(){
    if(!this.data.login){
      this.setData({needLogin:true})
      return;
    }
    if(!this.data.wzinfo){
      wx.showModal({
        content: '请先添加排查点',showCancel:false
      })
      return;
    }
    this.setData({
        'img':this.data.server+'/app/wx/scan/qrcontent.jpg?address='+this.data.ld+"&server="+this.data.server+'&appId='+server.getUserToken().id
    })
    this.setData({erweima:true})
  },
  hewm(){
    this.setData({erweima:false})
  },
  history(){
    if(!this.data.login){
      this.setData({needLogin:true})
      return;
    }
    wx.navigateTo({
      url: '/pages/record/record',
    });
  },
  bingXq(e){
      this.setData({xq:e.detail.value.replace(/\s*/g,"")});
  },
  bindDong(e){
    this.setData({dong:e.detail.value.replace(/\s*/g,"")});
  },
  bindDanyuan(e){
    this.setData({danyuan:e.detail.value.replace(/\s*/g,"")});
  },
  bingShi(e){
    this.setData({shi:e.detail.value.replace(/\s*/g,"")});
  },
  binglu(e){
    this.setData({lu:e.detail.value.replace(/\s*/g,"")});
  },
  binghao(e){
    this.setData({hao:e.detail.value.replace(/\s*/g,"")});
  },
  bingkd(e){
    this.setData({kd:e.detail.value.replace(/\s*/g,"")});
  },
  updateAddress(){
    this.setData({havaInfo:true});
  },
  initData(){
    let hh=wx.getStorageSync('havaInfo');
    if(hh){
        this.setData({havaInfo:hh});
    }
    this.setData({
      'xz':wx.getStorageSync('xz'),
      'cj':wx.getStorageSync('cj'),
      'type':wx.getStorageSync('type'),
      'dong':wx.getStorageSync('dong'),
      'xq':wx.getStorageSync('xq'),
      'danyuan':wx.getStorageSync('danyuan'),
      'shi':wx.getStorageSync('shi'),
      'kd':wx.getStorageSync('kd'),
      'lu':wx.getStorageSync('lu'),
      'hao':wx.getStorageSync('hao'),
      'xz':wx.getStorageSync('xz'),
      'wzinfo':wx.getStorageSync('wzinfo'),
      'lat':wx.getStorageSync('lat'),
      'long':wx.getStorageSync('long'),
      'ld':wx.getStorageSync('ld'),
      'isClose':wx.getStorageSync('isClose')||this.data.isClose,
      'isRent':wx.getStorageSync('isRent')||this.data.isRent,
      'type':wx.getStorageSync('type')||1
    });
  },
  validation: function() {
    if (this.data.xz == '') {
      this.data.error = '乡镇不能为空';
      return false;
    }
    if (this.data.cj == '') {
      this.data.error = '村居/社区不能为空';
      return false;
    }
    if (this.data.type == '') {
      this.data.error = '类型不能为空';
      return false;
    }
    if(this.data.type==3){
      if (this.data.kd == '') {
        this.data.error = '卡点名称不能为空';
        return false;
      }
    }else if(this.data.type==2){
      if (this.data.lu == '') {
        this.data.error = '路/街不能为空';
        return false;
      }
      if (this.data.hao == '') {
        this.data.error = '门牌号不能为空';
        return false;
      }
    }else if(this.data.type==1){
      if (this.data.xq == '') {
        this.data.error = '小区名不能为空';
        return false;
      }
      if (this.data.dong == '') {
        this.data.error = '幢不能为空';
        return false;
      }
      if (this.data.danyuan == '') {
        this.data.error = '单元不能为空';
        return false;
      }
      if (this.data.shi == '') {
        this.data.error = '室不能为空';
        return false;
      }
    }
    return true;
  },
  saveAddress(){
    if (!this.validation()) {
      wx.showModal({
        title:'友情提示',
        content: this.data.error,
        showCancel: false
      });
      return false;
    }
    let wzinfo=this.data.xz+this.data.cj;
    if(this.data.type=="1"){
      wzinfo+=this.data.xq+this.data.dong+"幢"+this.data.danyuan+"单元"+this.data.shi+"室";
    }else if(this.data.type=='2'){
      wzinfo+=this.data.lu+"路"+this.data.hao+"号";
    }else{
      wzinfo+=this.data.kd;
    }
    this.setData({wzinfo:wzinfo})
    wx.setStorageSync('isClose', this.data.isClose);
    wx.setStorageSync('isRent', this.data.isRent);
    wx.setStorageSync('xz', this.data.xz);
    wx.setStorageSync('cj', this.data.cj);
    wx.setStorageSync('type', this.data.type);
    wx.setStorageSync('dong', this.data.dong);
    wx.setStorageSync('xq', this.data.xq);
    wx.setStorageSync('danyuan', this.data.danyuan);
    wx.setStorageSync('shi', this.data.shi);
    wx.setStorageSync('kd', this.data.kd);
    wx.setStorageSync('lu', this.data.lu);
    wx.setStorageSync('hao', this.data.hao);
    wx.setStorageSync('wzinfo', wzinfo);
    wx.setStorageSync('havaInfo', false);
    let typeText = ''
    if(this.data.type==3){
      typeText='卡点'
    }else{
      typeText=''
    }
    this.setData({typeText})
    wx.setStorageSync('typeText', typeText)
    this.setData({havaInfo:false});
    this.getLocation()
  }
})
